﻿var HandleDom = {
    IdTriggerClick: function (controlId, callback) {
        $("#" + controlId).live("click", callback);
    },
    ClassTriggerClick: function (controlClass, callback) {
        $("." + controlClass).live("click", callback);
    },
    ClassTriggerDoubleClick: function (controlClass, callback) {
        $("." + controlClass).live("dblclick", callback);
    },
    IdTriggerBlur: function (controlId, callback) {
        $("#" + controlId).blur(callback);
    },
    IdTriggerChange: function (controlId, callback) {
        $("#" + controlId).change(callback);
    }

};

var HandleData = {
    GetDataGridSelected: function (dataGridId) {
        return $('#' + dataGridId).datagrid('getSelected');
    },
    GetTreeGridSelected: function (treeGridId) {
        return $('#' + treeGridId).treegrid('getSelected');
    },
    GetValueComboTree: function (comboTreeId) {
        return $('#' + comboTreeId).combotree('getValue');
    },
    GetValueComboBox: function (comboBoxId) {
        return $('#' + comboBoxId).combobox('getValue');
    },
    SetValueComboTree: function (comboTreeId, value) {
        $('#' + comboTreeId).combotree('setValue', value);
    },
    SetValueComboBox: function (comboBoxId, value) {
        $('#' + comboBoxId).combobox('setValue', value);
    },
    SetValueNumberSpinner: function (numberSpinnerId, value) {
        $('#' + numberSpinnerId).numberspinner('setValue', value);
    },
    IsNull: function (rowData, callback) {
        if (rowData) {
            if (callback != undefined) {
                callback();
            }
        } else {
            HandleTips.Alert('请先选中一条数据，再进行相关操作！');
            //$('#dlg').dialog('close');
        }
    },
    LoadForm: function (formId, row) {
        $('#' + formId).form('load', row);
    },
    ClearForm: function (formId) {
        $('#' + formId).form('clear');
    },
    ReloadDataGrid: function (dataGridId) {

        $('#' + dataGridId).datagrid('reload');
    },
    ReloadTreeGrid: function (treeGridId) {

        $('#' + treeGridId).treegrid('reload');
    },
    TreeGridExpandTo: function (treeGridId, nodeId) {
        $("#" + treeGridId).treegrid("expandTo", nodeId);
    },
    SelectTreeGridRow: function (treeGridId, nodeId) {
        $("#" + treeGridId).treegrid("select", nodeId);
    },
    InitDataGrid: function (dataGridId, url, toolbar, queryParams, idField, isSingle, loadSuccessCallback, doubleClickRowCallback, clickRowCallback, clickCellback, doubleClickCallback, loadErrorCallback) {
        if (!loadErrorCallback)
        {
            loadErrorCallback = function () {
                alert("数据加载失败");
                $("#" + dataGridId).datagrid('loadData', { total: 0, rows: [] });
            };
        }
        $("#" + dataGridId).datagrid({
            pageList: [10, 20, 50, 100],
            fit: true,
            queryParams: queryParams,
            rownumbers: true,
            singleSelect: isSingle,
            pagination: true,
            pageNumber:1,
            pageSize: 20,
            url: url,
            idField: idField,
            method: 'get',
            toolbar: '#' + toolbar,
            fitColumns: true,
            rowStyler:function(index,row){   
                if (row.ISSHOW==0){   
                    return 'background-color:red;';   
                }   
            } ,
            onLoadSuccess: loadSuccessCallback,//初始化事件
            onLoadError:loadErrorCallback,   // 加载失败事件
            onDblClickRow: doubleClickRowCallback,//双击行事件
            onClickRow: clickRowCallback,//单击行事件
            onClickCell: clickCellback,//单击单元格事件
            onDblClickCell: doubleClickCallback//双击单元格事件
        });
    },
    ///初始化 Datagrid 分页的 ，
    InitDataGridPage: function (dataGridId, url, queryParams, colmns, otherParamm, loadSuccessCallback, doubleClickRowCallback,loadErrorCallback)
    {
        if (!loadErrorCallback)
        {
            loadErrorCallback = function () {
                alert("数据加载失败");
                $("#" + dataGridId).datagrid('loadData', { total: 0, rows: [] });
            };
        }
        var loadSuccessFun = function (data)
        {
            if (!data || !data.rows || data.rows.length == 0) return;

            var fields = $("#" + dataGridId).datagrid('getColumnFields', false);
            var rows = $(".datagrid-view2 .datagrid-body table tr.datagrid-row");
            var type = {};
            $.each(data.rows[0],function (name, value)
            {
                type[name] = $.isNumeric(value); //是否数字
            });
            rows.each(function (i, item)
            {
                //datagrid主体 table 的每一个tr 的td们
                var tds = $(item).children();
                tds.each(function (itd, td)
                {
                    //获取当前列的信息
                    var col = $("#" + dataGridId).datagrid('getColumnOption', fields[itd]);
                    if (!col.hidden && !col.checkbox)
                    {
                        var align = 'left';
                        if (type[col.field])   //若数字型，则右对齐
                            align = 'right';
                        var dataalign = col.dataalign || col.align || align;
                        $("div:first-child", td).css("text-align", dataalign);
                    }
                });
            });
            if (loadSuccessCallback)
                loadSuccessCallback(data);
        }
        var idField="Id", toolbar = "toolbar", singleSelect = true;
        if (otherParamm) {
            idField = otherParamm["idField"] || idField;
            toolbar = otherParamm["toolbar"] || toolbar;
            singleSelect = otherParamm["singleSelect"] || singleSelect;
        }
        $("#" + dataGridId).datagrid({
            url: url,
            queryParams: queryParams,
            columns: colmns,
            pageList: [10, 20, 50, 100],
            fit: true,
            rownumbers: true,
            singleSelect: singleSelect,
            pagination: true,
            pageNumber:1,
            pageSize: 20,           
            idField: idField,
            method: 'get',
            toolbar: '#' + toolbar,
            fitColumns: true,
            rowStyler:function(index,row){   
                if (row.ISSHOW==0){   
                    return 'background-color:red;';   
                }   
            } ,
            onLoadSuccess: loadSuccessFun,//初始化事件
            onLoadError:loadErrorCallback,   // 加载失败事件
            onDblClickRow: doubleClickRowCallback,//双击行事件
           // onClickRow: clickRowCallback,//单击行事件
           // onClickCell: clickCellback,//单击单元格事件
           // onDblClickCell: doubleClickCallback//双击单元格事件
        });
    },
    InitTreeGrid: function (treeGridId, url, toolbar, idField, treeField, defaultSortField, loadSuccessCallback, doubleClickRowCallback, clickRowCallback, contextMenuCallback) {
        $("#" + treeGridId).treegrid({
            fit: true,
            animate: true,
            rownumbers: true,
            singleSelect: true,
            url: url,
            method: 'get',
            idField: idField,
            treeField: treeField,
            toolbar: '#' + toolbar,
            sortName: defaultSortField,
            sortOrder: 'asc',
            fitColumns: true,
            onLoadSuccess: loadSuccessCallback,
            onDblClickRow: doubleClickRowCallback,
            onClickRow: clickRowCallback,
            onContextMenu: contextMenuCallback
        });
    },
    InitCombotree: function (controlId, url, onSelectCallBack, loadSuccessCallback) {
        $('#' + controlId).combotree({
            url: url,
            method: 'get',           
            onSelect: onSelectCallBack,
            onLoadSuccess: loadSuccessCallback
        });
    },
    //combobox的初始化
    InitCombobox: function (controlId, url, valueField, textField, value, onSelectCallBack, multiple)
    {   
        $('#' + controlId).combobox({
            url: url,
            method: 'get',
            valueField: valueField,
            textField: textField,
            value: value,
            multiple: multiple,
            panelHeight: 'auto',
            onSelect: onSelectCallBack,
        });
    },
    InitMenu: function (menuId, clickCallBack) {
        $('#' + menuId).menu({
            onClick: clickCallBack
        });
    },
    HandleDataGridSaveResult: function (data, isClose, formId, dialogId, dataGridId, callback) {
        if (data != null && data.State) {
            HandleData.ReloadDataGrid(dataGridId);
            if (isClose) {
                HandleDialog.CloseDialog(dialogId);
                if (callback != undefined) {
                    callback();
                }
            } else {
                HandleData.ClearForm(formId);
                if (callback != undefined) {
                    callback();
                }
            }
        } else {
            HandleTips.Alert(data.Message);
        }
    },
    HandleTreeGridSaveResult: function (data, isClose, formId, dialogId, dataGridId, callback) {
        if (data != null && data.State) {
            HandleData.ReloadTreeGrid(dataGridId);
            if (isClose) {
                HandleData.ClearForm(formId);
                HandleDialog.CloseDialog(dialogId);
                if (callback != undefined) {
                    callback();
                }
            } else {
                HandleData.ClearForm(formId);
                if (callback != undefined) {
                    callback();
                }


            }
        }
    },
    HandleDialogSaveResult: function (data, dialogId) {
        if (data != null && data.State) {
            HandleDialog.CloseDialog(dialogId);
        }
    },
    HandleExsitResult: function (data, controlId, tips) {
        data = JSON.parse(data);
        if (data != null && data.State === true) {
            $("#" + controlId).val("");
            $.messager.alert('操作提示', tips, 'info');
        }
    },
    HandleDataGridRemoveResult: function (data, dataGridId) {
        data = JSON.parse(data);
        if (data != null && data.State === true) {
            $.messager.alert('操作提示', '删除数据成功!', 'info');
        } else {
            $.messager.alert('操作提示', '删除数据失败!' + data.Message, 'info');
        }
        HandleData.ReloadDataGrid(dataGridId);
    },
    HandleTreeGridRemoveResult: function (data, treeGridId) {
        data = JSON.parse(data);
        if (data != null && data.State === true) {
            $.messager.alert('操作提示', '删除数据成功!', 'info');
        } else {
            $.messager.alert('操作提示', '删除数据失败!', 'info');
        }
        HandleData.ReloadTreeGrid(treeGridId);
    }


};
var HandleTips = {
    Alert: function (content) {
        $.messager.alert('操作提示', content, 'info');
    },
    confirm: function (content, fun)
    {
        $.messager.confirm('操作提示', content, fun);
    },
    openLoading: function (title, msg, text)
    {
        if(!title) title='请等待';
        if(!msg) msg='处理中...';
        if(!text) text='正在处理中.......';
        $.messager.progress({
            title: title,
            msg: msg,
            text: text
        });
    },
    closeLoading: function ()
    {
        $.messager.progress('close');
    }
};
var HandleRequest = {
    submitRequest: function (url, paras, callback) {
        $.post(url, paras, callback);
    },
    submitForm: function (formId, url, callback, validateCallback) {
        $("#" + formId).form('submit', {
            url: url,
            onSubmit: function () {
                if (validateCallback != undefined) {
                    return validateCallback();
                }
                return $(this).form('validate');
            },
            success: callback
        });
    },
    getUrlPara: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var result = window.location.search.substr(1).match(reg);
        if (result != null) {
            return decodeURIComponent(result[2]);
        } else {
            return "undefined";
        }
    }
};

var Validate = {
    IsNotNull: function (value) {
        return value != null;
    },
    IsNotEmpty: function (value) {
        return value !== "";
    },
    IsNotNullOrEmpty: function (value) {
        return value != null && value != "";
    },
    JsonIsNotNull: function (value) {
        return value != null;
    },
    JsonIsNotNullOrEmpty: function (value) {
        return value != null && value.length > 0;
    }
}

$.log = function (format,val,val1,val2,val3,val4,val5)
{
    if (console.log)
    {        
        if (val)
            console.log(format, val, val1, val2, val3, val4, val5);
        else
            console.log(format);
    }       
}

//------------

$.Combobox = {
    changeSearchInput: function (containId)
    {
        var list, expr = "[type='text'][autocomplete]";
        if (containId)
            list = $("#" + containId).find(expr);
        else
            list = $(expr);
        list.each(function ()
        {            
            try
            {
                this.type = "search";
            }
            catch (ex) { }
        });
    },
    CellNoList: function (controlId, isSetAll, allValue, onSelectCallBack)
    {
        if ($("#" + controlId).length == 0) return;

        var url = "/BaseData/CellNoList", valueField = "FIELDVALUE", textField = "CELLNO";
        var value = null;
        if (isSetAll != null) {
            url += "?IsSetAll=" + isSetAll;
            if (allValue != null)
                url += "&AllValue=" + allValue;
            value = -1;
        }
        HandleData.InitCombobox(controlId, url, valueField, textField, value, onSelectCallBack);
    },
    CellNoList_ERP: function (controlId, isSetAll, onSelectCallBack) {
        if ($("#" + controlId).length == 0) return;

        var url = "/BaseData/CellNoListERP", valueField = "CELLNO", textField = "CELLNO";
        var value = null;
        if (isSetAll != null)
        {
            url += "?IsSetAll=" + isSetAll;
            value = "全部";
        }
        HandleData.InitCombobox(controlId, url, valueField, textField, value,onSelectCallBack);
    },
    VenderList:function(controlId, onSelectCallBack)
    {
        if ($("#" + controlId).length == 0) return;

        var url = "/BaseData/VenderList", valueField = "CODE", textField = "NAME";
        HandleData.InitCombobox(controlId, url, valueField, textField, onSelectCallBack);
    },
    OrderFlagList: function (controlId, onSelectCallBack)
    {
        if ($("#" + controlId).length == 0) return;

        var url = "/BaseData/OrderFlagList", valueField = "CODE", textField = "NAME";
        HandleData.InitCombobox(controlId, url, valueField, textField, onSelectCallBack);
    },
    DownOrderFlagList: function (controlId, onSelectCallBack)
    {
        if ($("#" + controlId).length == 0) return;

        var url = "/BaseData/DownOrderFlagList", valueField = "CODE", textField = "NAME";
        HandleData.InitCombobox(controlId, url, valueField, textField, onSelectCallBack);
    },
    LocationTypeList: function (controlId, onSelectCallBack)
    {
        if ($("#" + controlId).length == 0) return;

        var url = "/BaseData/LocationTypeList", valueField = "NAME", textField = "NAME";
        HandleData.InitCombobox(controlId, url, valueField, textField, onSelectCallBack);
    },
    WarehouseList: function (controlId, onSelectCallBack)
    {
        if ($("#" + controlId).length == 0) return;

        var url = "/BaseData/WarehouseList", valueField = "CODE", textField = "NAME";
        HandleData.InitCombobox(controlId, url, valueField, textField, onSelectCallBack);
    },
    UpObjectTypeList: function (controlId, onSelectCallBack) {
        if ($("#" + controlId).length == 0) return;

        var url = "/BaseData/UpObjectTypeList", valueField = "NAME", textField = "NAME";
        HandleData.InitCombobox(controlId, url, valueField, textField, onSelectCallBack);
    },
    DownObjectTypeList: function (controlId, onSelectCallBack)
    {
        if ($("#" + controlId).length == 0) return;

        var url = "/BaseData/DownObjectTypeList", valueField = "NAME", textField = "NAME";
        HandleData.InitCombobox(controlId, url, valueField, textField, onSelectCallBack);
    },    
    DownTypeList: function (controlId, onSelectCallBack)
    {
        if ($("#" + controlId).length == 0) return;

        var url = "/BaseData/DownTypeList", valueField = "NAME", textField = "NAME";
        HandleData.InitCombobox(controlId, url, valueField, textField, onSelectCallBack);
    },
    StatusList: function (controlId, onSelectCallBack)
    {
        if ($("#" + controlId).length == 0) return;

        var url = "/BaseData/StatusList", valueField = "CODE", textField = "NAME";
        HandleData.InitCombobox(controlId, url, valueField, textField, onSelectCallBack);
    }
}

//------------------easyui DataGrid 的扩展--------------------
$.dg = {
    formatDate:function (value, row, index)
    {
        if(!value)  return;
        return $.dateToString(value);
    },
    formatDateNoTime: function (value, row, index)
    {
        if(!value)  return;
        return $.dateToString(value,"yyyy-MM-dd");
    },
    formateNumber:function(value,row,index)
    {
        if (value == null) return;
        return parseFloat(value).toFixed(2);
    }
}

//----------Jquery Ext---------------
$.ajaxUntity = function (type, url, data, dataType, funSuccess, funError) {
    if (!funError) {
        funError = function (XMLHttpRequest, textStatus, errorThrown) {
            alert("请求失败");
            $.log("错误ajax url:%s", url);
           // this; // 调用本次AJAX请求时传递的options参数
        }
    }
    $.ajax({
        type: type,         //请求类型,get post
        url: url,
        data: data,             //传入参数
        dataType: dataType,    //返回类型
        success: funSuccess,    //成功 
        error: funError         //失败
    });
}

$.ajaxGet = function (url, data, funSuccess) {
    $.ajaxUntity("get", url, data, "json", funSuccess);
}

$.ajaxPost = function (url, data, funSuccess) {
    $.ajaxUntity("post", url, data, "json", funSuccess);
}
//----------------- 日期扩展
$.dateToString=function(dateString,formate)
{
    if(typeof XDate == 'undefined')
   // if (!XDate)
    {
        $.log("未加载common\\xdata.js ");
        return;
    }
    if (!formate)
        formate = "yyyy-MM-dd HH:mm:ss";
    return new XDate(dateString).toString(formate);
}


//---------------------其他扩展
//获取url参数值， name:参数名
$.getQueryString=function(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

//通过表单 转成json格式数据
$.formToJson = function (formId)
{
    var $form = $('#' + formId);
    $form.find("[type='search'],[type='text']").each(function ()
    {
        var val = $(this).val();
        if(val.length>0)  //u空格 
            $(this).val($.trim(val));
    });
    var data = $form.serialize(); //获取值
    data = decodeURIComponent(data, true);
    data=data.replace(/&/g,"\",\"");
    data=data.replace(/=/g,"\":\"");
    data="{\""+data+"\"}";
    return $.parseJSON(data);
}

//触发回车 键盘  事件绑定 
$.initKeyDown=function(btnId)
{
    //按回车 触发 查询
    document.onkeydown = function (e)
    {
        var theEvent = window.event || e;
        var code = theEvent.keyCode || theEvent.which;
        if (code == 13)
        {
            $("#" + btnId).click();
        }
    }
}



